<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
          <!-- <template v-slot:filter-inOrOutDepot>
            <slip-select
              v-model="filterInfo.query.inOrOutDepot"
              value-key="value"
              placeholder="选择出入库仓库"
              :api="inOrOutDepotInfo.api"
              :query="inOrOutDepotInfo.query"
              key-field="name"
              value-field="id"
              :clearable="true"
              :filterable="true"
              :multiple="false"
              @change="search"
            />
          </template> -->
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList"> </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :summary="true"
        :summary-field-list="tableInfo.summaryFieldList"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :tabIndex="true"
        :check-box="false"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </TableContainer>
    </div>
    <TransferOrderModify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :orderId="modifyInfo.orderId"
      :receiveData="modifyInfo.receiveData"
      :isCargoSpaceManage="modifyInfo.isCargoSpaceManage"
      :dept="modifyInfo.dept"
      :isConsignBusiness="modifyInfo.isConsignBusiness"
      @returnModify="returnModify"
    />
    <TransferOrderDetail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row="detailInfo.data"
      @returnBack="getList"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <AddByReceiveOrder
      v-if="addReceiveDialog.visible"
      v-model:showDialog="addReceiveDialog.visible"
      :checkBox="false"
      :highlightRow="true"
      @callback="addReceiveOrderBack"
    />
    <PageDialog
      v-show="dialogUserInfo.visible"
      :title="dialogUserInfo.title"
      v-model:visible="dialogUserInfo.visible"
      :width="dialogUserInfo.width"
      :bt-loading="dialogUserInfo.btLoading"
      :bt-list="dialogUserInfo.btList"
      @reset="handleClose"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formUserInfo.ref"
        :data="formUserInfo.data"
        :field-list="formUserInfo.fieldList"
        :label-width="formUserInfo.labelWidth"
        :list-type-info="listTypeInfo"
      >
      </page-form>
    </PageDialog>
  </div>
</template>

<script setup name="transferOrder">
import {
  receivingImportTransfers,
  getTransferOrderCustomizeList,
  removeTransferOrder,
  submitTransferOrder,
  transferTransferOrder,
  tallyTransferOrder,
  revokeTransferOrder,
  transferAndPutShelf,
  checkTransferOrder,
  rejectTransferOrder,
  transferCancelPut,
  transfersCancel,
  transfersCancelDownShelf,
} from '@/api/stock.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import TableContainer from '@/components/TableContainer/index'
import NewPageFilter from '@/components/NewPageFilter/index'
import TransferOrderModify from './modify'
import TransferOrderDetail from './detail'
import AddByReceiveOrder from './addByReceiveOrder'
import PageDialog from '@/components/PageDialog/index'
import PageForm from '@/components/PageForm/index'
import { getRrgUserAll } from '@/api/base.js'
import { getDepotAll } from '@/api/core'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/defaultSetPreference')
)
const AdvancedSearch = defineAsyncComponent(() =>
  import('@/components/AdvancedSearch/index')
)
const detailList = defineAsyncComponent(() => import('./detailList'))

const clearType = ref(true)
const slipSelectRequest = ref(true)
const time = ref([])
const addReceiveDialog = reactive({
  visible: false,
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    queryMap: {},
    queryParams: {},
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('transferOrder:add'),
    },
    {
      type: 'button',
      label: '收货单导入',
      event: receivingImport,
      show: proxy.$permission('transferOrder:receivingImport'),
    },
  ],
})
//出入库查询
// const inOrOutDepotInfo = reactive({
//   api: getDepotAll,
//   query: {
//     depotAuth: 'id',
//     status: 1,
//     useTypeId: 1,
//   },
// })
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  summaryFieldList: [
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('transferOrder:submit'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '审核',
        event: check,
        show:
          proxy.$store.state.permission.systemConfig.move_stock_approval ===
            1 && proxy.$permission('transferOrder:check'),
        ifRender: function (row) {
          return row.status === 4
        },
      },
      {
        label: '驳回',
        event: reject,
        show:
          proxy.$store.state.permission.systemConfig.move_stock_approval ===
            1 && proxy.$permission('transferOrder:reject'),
        ifRender: function (row) {
          return row.status === 4
        },
      },
      {
        label: '撤回',
        event: revoke,
        show: proxy.$permission('transferOrder:revoke'),
        ifRender: ifRenderRevoke,
      },
      {
        label: '移库',
        event: transfer,
        show: proxy.$permission('transferOrder:transfer'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '取消',
        event: doCancel,
        show: proxy.$permission('transferOrder:cancel'),
        ifRender: function (row) {
          return row.status === 2 && row.exportDepotIsCargoSpaceManage === 1
        },
      },
      {
        label: '取消上架',
        event: doCancelPut,
        show: proxy.$permission('transferOrder:cancelPut'),
        ifRender: function (row) {
          return row.status === 5
        },
      },
      {
        label: '取消拣货',
        event: doCancelDown,
        show: proxy.$permission('transferOrder:cancelDown'),
        ifRender: function (row) {
          return row.status === 6
        },
      },
      // {
      //   label: '移库并上架',
      //   event: transferPutShelf,
      //   show: proxy.$permission('transferOrder:transferAndPutShelf'),
      //   ifRender: function (row) {
      //     return row.status === 2 && row.isCargoSpaceManage === 1
      //   },
      // },
      {
        label: '移库消耗',
        event: tally,
        show: proxy.$permission('transferOrder:tally'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('transferOrder:update'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: remove,
        show: proxy.$permission('transferOrder:delete'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
    ],
  },
})
const modifyInfo = reactive({
  visible: false,
  title: '',
  returnStoreId: '',
  receiveData: [],
  isCargoSpaceManage: 0,
  dept: {},
  isConsignBusiness: null,
})
const detailInfo = reactive({
  visible: false,
  data: {},
})
const printerInfo = reactive({
  visible: false,
  data: {},
})
const detailListInfo = reactive({
  visible: false,
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})

const dialogUserInfo = reactive({
  type: '',
  visible: false,
  title: '选择上架人员',
  btLoading: false,
  width: '400px',
  btList: [
    {
      label: '关闭',
      event: handleClose,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      event: savePutShelfUser,
      show: true,
    },
  ],
})
const formUserInfo = reactive({
  data: {
    id: '',
    putShelfUser: -2,
  },
  fieldList: [
    {
      label: '姓名',
      value: 'putShelfUser',
      type: 'select',
      filterable: true,
      list: 'userList',
      event: 'userName',
    },
  ],
})
const listTypeInfo = reactive({
  userList: [],
})

let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'transfer_order_status',
    show: false,
    hidden: true,
  },
  inOrOutDepot: {
    label: '出入库仓库',
    value: 'inOrOutDepot',
    componentType: 'slip-select',
    query: {
      depotAuth: 'id',
      status: 1,
      useTypeId: '1',
    },
    api: getDepotAll,
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
getUserList()

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'transferOrder' && el.url === val.url) {
                detailInfo.visible = false
                modifyInfo.visible = false
                detailInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.visible = true
                    detailInfo.data = {
                      id: val.orderId || val.businessId,
                      orderNo: val.orderNo || '',
                    }
                    sessionStorage.setItem(
                      'storeRowId',
                      val.orderId || val.businessId
                    )
                    console.log(detailInfo, 11111111)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

function receivingImport() {
  addReceiveDialog.visible = true
}
function addReceiveOrderBack(data) {
  if (data && data.id) {
    receivingImportTransfers(data.id).then((res) => {
      if (res && res.success) {
        addReceiveDialog.visible = false
        proxy.$nextTick(() => {
          res.data.forEach((item) => {
            if (item.calcQty > item.stockAvailableCalcQty) {
              item.calcQty = proxy.$fn.deepClone(item.stockAvailableCalcQty)
              item.qty = proxy.$fn.deepClone(item.stockAvailableQty)
              item.largeUnitQty = parseInt(
                item.calcQty / item.unitConvertCoefficient
              )
              item.smallUnitQty = parseInt(
                item.calcQty % item.unitConvertCoefficient
              )
              item.sumAmount = proxy.$fn.accDiv(
                proxy.$fn.accMul(item.calcQty || 0, item.price || 0),
                item.unitConvertCoefficient || 1
              )
            }
          })
          modifyInfo.orderId = ''
          modifyInfo.title = '新增移库单'
          modifyInfo.visible = true

          modifyInfo.receiveData = res.data
          modifyInfo.dept.depotName = data.depotName
          modifyInfo.dept.depotId = data.depotId
          modifyInfo.dept.deptId = data.deptId
          modifyInfo.dept.deptName = data.deptName
          modifyInfo.isConsignBusiness = data.isConsignBusiness
          modifyInfo.isCargoSpaceManage = data.isCargoSpaceManage
        })
      }
    })
  }
}
function ifRenderRevoke(row = undefined) {
  if (proxy.$store.state.permission.systemConfig.move_stock_approval === 1) {
    return row.status === 4 && row.orderSourceType !== 75
  }
  return (
    row.status === 2 &&
    row.orderSourceType !== 75 &&
    row.exportDepotIsCargoSpaceManage === 0
  )
}
function returnModify() {
  if (modifyInfo.returnStoreId) {
    getList()
  } else {
    search()
  }
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'transfer_order',
      columnName: 'export_depot_id',
      queryType: 'IN',
      queryCategory: 'OR',
      value: 'depotAuth',
    },
    {
      asTbName: 'transfer_order',
      columnName: 'store_depot_id',
      queryType: 'IN',
      queryCategory: 'OR',
      value: 'depotAuth',
    },
  ]
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data
  await getList()
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
//删除
function remove(row) {
  if (row && row.id) {
    removeTransferOrder([row.id]).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  }
}
//创建
function create() {
  modifyInfo.orderId = ''
  modifyInfo.title = '新增移库单'
  modifyInfo.visible = true
  modifyInfo.receiveData = []
}
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.orderId = row.id
  modifyInfo.title = '修改移库单'
  modifyInfo.visible = true
  modifyInfo.receiveData = []
}
//提交
function submit(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  }
  submitTransferOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function check(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  }
  checkTransferOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function reject(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  }
  rejectTransferOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function transfer(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  transferTransferOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function doCancel(row = undefined) {
  transfersCancel(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}

function doCancelPut(row = undefined) {
  proxy
    .$confirm('确认取消上架吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      transferCancelPut(row.id).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
    .catch(() => {})
}
function doCancelDown(row = undefined) {
  proxy
    .$confirm('确认取消拣货吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      transfersCancelDownShelf(row.id).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
    .catch(() => {})
}

//获取人员列表
function getUserList() {
  let params = {
    sort: 'create_time desc',
  }
  getRrgUserAll(params).then((res) => {
    if (res && res.success) {
      let arr = [{ key: '暂不选择', value: -2, userName: '' }]
      if (res.data && res.data.length) {
        let data = res.data.map((item) => {
          return {
            key: item.name,
            value: item.id,
            userName: item.userName,
          }
        })
        listTypeInfo.userList = arr.concat(data)
      }
    }
  })
}
//上架
function savePutShelfUser() {
  transferAndPutShelf(formUserInfo.data).then((resp) => {
    if (resp && resp.success) {
      getList()
      handleClose()
    }
  })
}
//关闭选择拣货人员弹窗
function handleClose() {
  dialogUserInfo.visible = false
  formUserInfo.data = {
    id: '',
    putShelfUser: -2,
  }
}
function transferPutShelf(row = undefined) {
  dialogUserInfo.visible = true
  formUserInfo.data.id = row.id
}
function tally(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  tallyTransferOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function revoke(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  revokeTransferOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.data = row
  detailInfo.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
    case 'list':
      break
  }
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.queryMap.transferTime.value = val[0] + ',' + val[1]
  } else {
    filterInfo.value.query.queryMap.transferTime.value = ''
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  time.value = []
  advancedSearchInfo.data = {}
  getCustomize()
  //   filterInfo.value.query.queryMap = proxy.$fn.deepClone(
  //     filterInfo.value.copyQueryMap
  //   )
  //   search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'stockTransferOrderList-com.slip.spd.entity.vo.stock.TransferOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      const obj = {
        storeDepotAuth: {
          asTbName: 'transfer_order',
          columnName: 'store_depot_id',
          queryType: 'IN',
          queryCategory: 'OR',
          value: 'depotAuth',
        },
        exportDepotAuth: {
          asTbName: 'transfer_order',
          columnName: 'export_depot_id',
          queryType: 'IN',
          queryCategory: 'OR',
          value: 'depotAuth',
        },
      }
      filterInfo.value.query.queryMap = {
        ...filterInfo.value.query.queryMap,
        ...searchInfo.queryMap,
        ...obj,
      }
      //出入库查询条件
      // let inOrOutDepot = {
      //   slot: true,
      //   value: 'inOrOutDepot',
      // }
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getTransferOrderCustomizeList
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
